package com.youlai.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.common.util.DateUtils;
import com.youlai.system.common.util.IpUtil;
import com.youlai.system.converter.CarUserConverter;
import com.youlai.system.mapper.CarUserMapper;
import com.youlai.system.model.bo.UserFormBO;
import com.youlai.system.model.dto.UserAuthInfo;
import com.youlai.system.model.entity.CarUser;
import com.youlai.system.model.form.CarUserForm;
import com.youlai.system.model.form.UserForm;
import com.youlai.system.model.query.CarUserPageQuery;
import com.youlai.system.model.query.UserPageQuery;
import com.youlai.system.model.vo.*;
import com.youlai.system.security.util.SecurityUtils;
import com.youlai.system.service.CarUserService;
import com.youlai.system.service.SysMenuService;
import com.youlai.system.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户业务实现类
 *
 * @author haoxr
 * @since 2022/1/14
 */
@Service
@RequiredArgsConstructor
public class CarUserServiceImpl extends ServiceImpl<CarUserMapper, CarUser> implements CarUserService {


    private final CarUserConverter userConverter;

    private final SysMenuService menuService;

    private final SysRoleService roleService;


    /**
     * 获取用户分页列表
     *
     * @param queryParams
     * @return
     */
    @Override
    public IPage<CarUserPageVO> getUserPage(CarUserPageQuery queryParams) {

        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarUserPageVO> page = new Page<>(pageNum, pageSize);

        // 格式化为数据库日期格式，避免日期比较使用格式化函数导致索引失效
        if(StringUtils.isNotEmpty(queryParams.getStartTime()) && StringUtils.isNotEmpty(queryParams.getEndTime())) {
            DateUtils.toDatabaseFormat(queryParams, "startTime", "endTime");
        }
        // 查询数据
        Page<CarUserPageVO> userPage = this.baseMapper.getUserPage(page, queryParams);
        userPage.getRecords().forEach(item->{
            CarUserPageQuery queryParamsTemp=new CarUserPageQuery();
            queryParamsTemp.setUserId(item.getUserId());
            List<CarAuthPageVO>  pages=this.baseMapper.selectMyGarageList(queryParamsTemp);
            item.setCarAuthList(pages);
            try {
                String ip= null;
                if(StringUtils.isNotEmpty(item.getIpAddr())) {
                    ip = IpUtil.getAddress(item.getIpAddr());
                    String[] adr = ip.split("\\|");
                    if (adr != null && adr.length >= 3) {
                        String city = adr[2].replace("省", "");
                        if ("台湾".equals(city)) {
                            city = "中国台湾";
                        }
                        item.setIpAddr(item.getIpAddr() + " " + city);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        // 实体转换
        return userPage;
    }

    /**
     * 获取用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public UserForm getUserFormData(Long userId) {
        UserFormBO userFormBO = this.baseMapper.getUserDetail(userId);
        // 实体转换po->form
        UserForm userForm = userConverter.bo2Form(userFormBO);
        return userForm;
    }


    /**
     * 更新用户
     *
     * @param userId   用户ID
     * @param userForm 用户表单对象
     * @return
     */
    @Override
    @Transactional
    public boolean updateUser(Long userId, UserForm userForm) {

        String username = userForm.getUsername();

        long count = this.count(new LambdaQueryWrapper<CarUser>()
                .eq(CarUser::getLoginName, username)
                .ne(CarUser::getUserId, userId)
        );
        Assert.isTrue(count == 0, "用户名已存在");

        // form -> entity
        CarUser entity = userConverter.form2Entity(userForm);

        // 修改用户
        boolean result = this.updateById(entity);


        return result;
    }

    /**
     * 删除用户
     *
     * @param idsStr 用户ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteUsers(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的用户数据为空");
        // 逻辑删除
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return this.removeByIds(ids);

    }

    /**
     * 修改用户密码
     *
     * @param userId   用户ID
     * @param password 用户密码
     * @return true|false
     */


    /**
     * 根据用户名获取认证信息
     *
     * @param username 用户名
     * @return 用户认证信息 {@link UserAuthInfo}
     */
    @Override
    public UserAuthInfo getUserAuthInfo(String username) {
        UserAuthInfo userAuthInfo = this.baseMapper.getUserAuthInfo(username);
        if (userAuthInfo != null) {
            Set<String> roles = userAuthInfo.getRoles();
            if (CollectionUtil.isNotEmpty(roles)) {
                Set<String> perms = menuService.listRolePerms(roles);
                userAuthInfo.setPerms(perms);
            }

            // 获取最大范围的数据权限
            Integer dataScope = roleService.getMaximumDataScope(roles);
            userAuthInfo.setDataScope(dataScope);
        }
        return userAuthInfo;
    }


    /**
     * 获取导出用户列表
     *
     * @param queryParams
     * @return
     */
    @Override
    public List<CarUserExportVO> listExportUsers(CarUserPageQuery queryParams) {
        List<CarUserExportVO> list = this.baseMapper.listExportUsers(queryParams);
        return list;
    }

    /**
     * 获取登录用户信息
     *
     * @return {@link UserInfoVO}   用户信息
     */
    @Override
    public UserInfoVO getCurrentUserInfo() {

        String username = SecurityUtils.getUser().getUsername(); // 登录用户名

        // 获取登录用户基础信息
        CarUser user = this.getOne(new LambdaQueryWrapper<CarUser>()
                .eq(CarUser::getLoginName, username)
                .select(
                        CarUser::getUserId,
                        CarUser::getNickName
                )
        );
        // entity->VO
        UserInfoVO userInfoVO = userConverter.toUserInfoVo(user);

        // 用户角色集合
        Set<String> roles = SecurityUtils.getRoles();
        userInfoVO.setRoles(roles);

        // 用户权限集合
        if (CollectionUtil.isNotEmpty(roles)) {
            Set<String> perms = menuService.listRolePerms(roles);
            userInfoVO.setPerms(perms);
        }
        return userInfoVO;
    }

    @Override
    public IPage<CarUserPageVO> getUserVipPage(CarUserPageQuery queryParams) {
        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarUserPageVO> page = new Page<>(pageNum, pageSize);
        if(StringUtils.isNotEmpty(queryParams.getStartTime()) && StringUtils.isNotEmpty(queryParams.getEndTime())) {
            // 格式化为数据库日期格式，避免日期比较使用格式化函数导致索引失效
            DateUtils.toDatabaseFormat(queryParams, "startTime", "endTime");
        }

        // 查询数据
        Page<CarUserPageVO> userPage = this.baseMapper.getUserVipPage(page, queryParams);

        // 实体转换
        return userPage;
    }

    @Override
    public CarUser getCarUser(Integer userId) {
        return this.baseMapper.selectUserById(userId);
    }

    @Override
    public boolean updateCarUser(Integer userId, CarUserForm userForm) {
        if("0".equals(userForm.getDisabledVal())){

            if(userForm.getStatus()==1){
                userForm.setStatus(4);
            }else if(userForm.getStatus()==5){
                userForm.setStatus(6);
            }else{
                userForm.setStatus(3);
            }

        }else{
            if(userForm.getStatus()==4||userForm.getStatus()==1){
                userForm.setStatus(1);
            }else if(userForm.getStatus()==6){
                userForm.setStatus(5);
            }else{
                userForm.setStatus(0);
            }
        }

        int result = this.baseMapper.updateCarUser(userForm);
        return  result>0;
    }

    @Override
    public boolean updateStatus(Integer userId) {
        CarUserForm userForm=new CarUserForm();
        userForm.setUserId(userId);
        userForm.setStatus(5);
        int result = this.baseMapper.updateCarUser(userForm);
        return  result>0;
    }

    @Override
    public IPage<CarAuthPageVO> getMyGaragePage(CarUserPageQuery queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarAuthPageVO> page = new Page<>(pageNum, pageSize);
        // 查询数据
        Page<CarAuthPageVO> userPage = this.baseMapper.selectMyGaragePage(page, queryParams);
        return userPage;
    }

    @Override
    public IPage<CarAdPageVO> getMyAdPage(CarUserPageQuery queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarAuthPageVO> page = new Page<>(pageNum, pageSize);
        // 查询数据
        Page<CarAdPageVO> userPage = this.baseMapper.selectMyAdPage(page, queryParams);

        // 实体转换
        return userPage;
    }

    @Override
    public IPage<CarUserPageVO> getMyLikePage(CarUserPageQuery queryParams) {
        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarUserPageVO> page = new Page<>(pageNum, pageSize);

        Page<CarUserPageVO> userPage = this.baseMapper.selectMyLikePage(page, queryParams);
        // 实体转换
        return userPage;
    }

    @Override
    public IPage<CarUserPageVO> getMyVisitorPage(CarUserPageQuery queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarUserPageVO> page = new Page<>(pageNum, pageSize);

        Page<CarUserPageVO> userPage = this.baseMapper.selectMyVisitorPage(page, queryParams);
        return userPage;
    }

    @Override
    public IPage<CarSharePageVO> getMySharePage(CarUserPageQuery queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarAuthPageVO> page = new Page<>(pageNum, pageSize);

        // 格式化为数据库日期格式，避免日期比较使用格式化函数导致索引失效
        if(StringUtils.isNotEmpty(queryParams.getStartTime()) && StringUtils.isNotEmpty(queryParams.getEndTime())) {
            DateUtils.toDatabaseFormat(queryParams, "startTime", "endTime");
        }

        // 查询数据
        Page<CarSharePageVO> userPage = this.baseMapper.selectMySharePage(page, queryParams);

        // 实体转换
        return userPage;
    }

    @Override
    public IPage<CarUserPageVO> getMyFollowPage(CarUserPageQuery queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarUserPageVO> page = new Page<>(pageNum, pageSize);

        Page<CarUserPageVO> userPage = this.baseMapper.selectMyFollowPage(page, queryParams);
        return userPage;
    }

    @Override
    public boolean saveImport(CarUserImportVO userImportVO) {
        int result=this.baseMapper.insertImport(userImportVO);
        return result>0;
    }

    @Override
    public IPage<CarAttPageVO> getUserAtrPage(CarUserPageQuery queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CarAttPageVO> page = new Page<>(pageNum, pageSize);
        Page<CarAttPageVO> userPage = this.baseMapper.selectUserAtrPage(page, queryParams);
        return userPage;
    }


}
